package com.hpe.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hpe.dao.*;
import com.hpe.pojo.*;
import com.hpe.service.SignService;
import com.hpe.service.StudentInfoService;
import com.hpe.util.DownloadUtil;
import com.hpe.util.ExcelUtil;
import com.hpe.util.ServerResponse;
import com.hpe.vo.EnterpriseInfo;
import com.hpe.vo.SignInfo;
import com.hpe.vo.SignVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.*;

@Service
public class SignServiceImpl implements SignService {

    @Autowired
    EnterpriseMapper enterpriseMapper;
    @Autowired
    EnterPostMapper enterPostMapper;
    @Autowired
    StudentInfoMapper studentInfoMapper;
    @Autowired
    SignMapper signMapper;
    @Autowired
    PostMapper postMapper;
    @Autowired
    SettingsMapper settingsMapper;

    private Logger logger = LoggerFactory.getLogger(StudentInfoService.class);

    @Override
    public PageInfo<EnterpriseInfo> getAllEnterpriseByType(Student student, Integer pageNum, Integer pageSize) {
        //获取当前学生详细信息
        StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(student.getId());
        PageInfo<EnterpriseInfo> pageInfo = null;
        if (studentInfo.getDirection() != null && !"".equals(studentInfo.getDirection())) {
            // 设置分页信息
            PageHelper.startPage(pageNum, pageSize);
            List<EnterpriseInfo> list = enterpriseMapper.getEnterpriseAllByType(Integer.parseInt(studentInfo.getDirection()));
            pageInfo = new PageInfo<>(list);
        }

        //返回成功信息
        return pageInfo;
    }

    @Override
    public List<SignInfo> getAllSignInfoByStuId(Student student) {
        //查询企业报名信息
        List<SignInfo> signInfos = signMapper.selectSignInfoByStudentId(student.getId());
        if (signInfos != null && signInfos.size() > 0) {
            return signInfos;
        }
        return null;
    }

    @Override
    public ServerResponse enterpriseSign(Student student, Integer enterpriseId, Integer postId) throws ParseException {
        //获取当前学生最大报名数
        Settings settings = settingsMapper.selectByCondition();
        //获取当前学生所有报名信息
        List<Sign> signs = signMapper.selectByStudentId(student.getId());
        int signTotal = signs.size();
        for (Sign sign : signs) {
            //根据企业id获取企业信息
            Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(sign.getEnterId());
            //企业报名已过期 报名数减去1
            if (enterprise.geteTime().before(Calendar.getInstance(TimeZone.getTimeZone("GMT+8")).getTime())) {
                signTotal--;
            }
        }
        //检验报名数
        if (settings.getMaxSign() <= signTotal) {
            return ServerResponse.createByErrorMsg("报名次数已用完！");
        }
        //根据id获取岗位信息
        Post post = postMapper.selectByPrimaryKey(postId);
        Sign sign = new Sign();
        //为sign属性赋值
        //设置岗位名称
        sign.setChoice(post.getName());
        //设置报名企业id
        sign.setEnterId(enterpriseId);
        sign.setsId(student.getId());
        //设置报名时间
        sign.setTime(new Date());
        //设置录取状态 -1 等待录取 0 未录取 1 已录取
        sign.setState(-1);
        //执行添加
        int insertResult = signMapper.insertSelective(sign);
        if (insertResult != 0) {
            return ServerResponse.createBySuccessMsg("报名成功");

        }
        return ServerResponse.createByErrorMsg("报名失败！");
    }

    @Override
    public ServerResponse<PageInfo<SignInfo>> getAllSignInfoByStuId(Student student, Integer pageNum, Integer pageSize) {
        // 设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        List<SignInfo> signInfos = signMapper.selectSignInfoByStudentId(student.getId());
        PageInfo<SignInfo> pageInfo = new PageInfo<>(signInfos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public List<SignInfo> signInfoByEnterId(Integer enterpriseId) {
        List<SignInfo> signInfos = signMapper.selectSignInfoByEnterpriseId(enterpriseId);
        if (signInfos == null || signInfos.size() == 0) {
            return null;
        }
        return signInfos;
    }

    @Override
    public ServerResponse inputSignInfo(InputStream inputStream) throws Exception {
        ExcelUtil excelUtil = new ExcelUtil(inputStream, "2007");
        String[] propertyNames = {"EpName", "EnterId", "sName", "sId", "ClassName", "Phone", "Choice", "Money", "Position", "TypeB", "TypeM", "State"};
        Class<?>[] propertyTypes = {String.class, Integer.class, String.class, Integer.class, String.class, String.class, String.class, String.class, String.class, Integer.class, Integer.class, Integer.class};
        //从导入文件中读取数据并封装到signVos中
        List<SignVo> signVos = null;
        try {
            signVos = excelUtil.readExcel(propertyNames, propertyTypes, SignVo.class);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ServerResponse.createByErrorMsg("文件解析出错，请确认每个单元格输入格式正确,且数据信息和导出表头信息相对应");
        }
        //学生录取状态信息保存
        Map<Integer, Integer> map = null;
        //从企业报名表中查询对应企业的所有学生，并装载map
        if (signVos != null && signVos.size() > 0) {
            map = new HashMap<>(signVos.size());
            //根据企业id获取学生报名信息
            List<SignVo> signVoList = signMapper.selectSignVoByEnterpriseId(signVos.get(0).getEnterId());
            //学生录取状态信息录入map
            for (SignVo signVo : signVoList) {
                map.put(signVo.getsId(), signVo.getState());
            }
        } else {
            return ServerResponse.createByErrorMsg("请上传一个有有效数据的文件");
        }
        for (SignVo signVo : signVos) {
            //判断导入学生录取状态是否已经更改，（录取状态只能更新一次）
            Integer status = map.get(signVo.getsId());
            if (status != -1) {
                continue;
            }

            Sign sign = new Sign();
            sign.setEnterId(signVo.getEnterId());
            sign.setsId(signVo.getsId());
            sign.setTypeB(signVo.getTypeB());
            sign.setTypeM(signVo.getTypeM());
            sign.setState(signVo.getState());
            int result = signMapper.updateByPrimaryKeySelective(sign);
            if (result <= 0) {
                return ServerResponse.createByErrorMsg("导入中途失败, 请重试");
            }
        }
        return ServerResponse.createBySuccessMsg("导入成功");
    }

    @Override
    public void outputSignInfo(HttpServletRequest request, HttpServletResponse response, Integer enterpriseId) throws Exception {
        //根据企业id获取报名表信息
        List<SignVo> signVos = signMapper.selectSignVoByEnterpriseId(enterpriseId);
        //根据企业id获取对应企业信息
        EnterpriseInfo enterprise = enterpriseMapper.getEnterpriseById(enterpriseId);
        //文件下载名设置
        String outputFileName = enterprise.getName();
        String[] beanProperty = {"EpName", "EnterId", "sName", "sId", "ClassName", "Phone", "Choice", "Money", "Position", "TypeB", "TypeM", "State"};
        String[] colName = {"企业名称", "企业Id", "学生姓名", "学生Id", "学生班级", "联系方式", "报名岗位", "薪资范围", "城市意向", "笔试情况(1.通过 0.未通过)", "面试情况(1.通过 0.未通过)", "录取情况(1.录取 0.未录取)"};
        int[] lock = {1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0};
        ExcelUtil excelUtil = new ExcelUtil("2007");
        ByteArrayOutputStream arrayOutputStream =
                excelUtil.getExcelStreamWithPointOutProperties(signVos.toArray(new SignVo[signVos.size()]), beanProperty, colName, outputFileName + "报名表", "", lock);

        new DownloadUtil().download(arrayOutputStream, response, request, outputFileName + "报名表.xlsx");
    }

    /**
     * @Author:HouPeng
     * @Description:学生报名信息 完善（薪资 城市完善）
     * @Date:19:35 2017/10/16
     * @param:sign 需要完善的信息
     * @return:
     */
    @Override
    public ServerResponse signInfoComplete(Sign sign) {
        Sign resultSign = signMapper.selectByPrimaryKey(sign);
        //校验是否被录取
        if (resultSign.getState() > 0) {
            //防止重复修改
            if (resultSign.getPosition() == null || resultSign.getMoney() == null) {
                //执行更新操作
                int result = signMapper.updateByPrimaryKeySelective(sign);
                if (result > 0) {
                    return ServerResponse.createBySuccessMsg("操作成功");
                }
            }
        }
        return ServerResponse.createByErrorMsg("操作失败");
    }

    /**
     * @param studentId 当前学生id
     * @Author:HouPeng
     * @Description:雷达图学生沟通维度数据计算
     * @Date:10:38 2017/10/23
     * @return:
     */
    @Override
    public int getCommunicateValueBuStudentId(Integer studentId) {
        List<Sign> signs = signMapper.selectByStudentId(studentId);
        //企业录取数
        int enrollNum = 0;
        //计算企业录取数
        for (Sign sign : signs) {
            if (sign.getState() == 1) {
                enrollNum++;
            }
        }
        //计算雷达图学生沟通维度的值（计算公式：x!=0时:y=10/x +10/x-1+...+ 60,x=0时:y=60）
        int commuicateValue = 60;
        if (enrollNum != 0) {
            while (enrollNum > 0) {
                commuicateValue += 10 / enrollNum;
                enrollNum--;
            }
        }

        //返回沟通维度结果
        return commuicateValue > 100 ? 100 : commuicateValue;
    }
}
